<template>
<li>
    <input type="checkbox" :checked="todo.check" @change="handleCheck" class="custom-checkbox"/>
    <span v-if="!editing" @dblclick.stop="editTodo" class="text"  :class="{ line: todo.check }">{{todo.value}}</span>
    <input
      v-else
      type="text"
      ref="editableInput"
      v-model="localTodoValue"
      @blur="saveTodo"
      @keyup.enter="saveTodo"
    />
    <span class="close" @click="handleDelete">x</span>
  </li>

</template>

<script setup>
import { ref, toRefs } from 'vue';

// 创建一个响应式引用来跟踪编辑状态
const editing = ref(false)
// 创建一个引用来存储可编辑的 input 元素
const editableInput = ref(null)

// 定义接收的 props
const props = defineProps({
  todo: {
    type: Object,
    required: true,
  },
  checkTodo: {
    type: Function,
    required: true,
  },
  deleteTodo: {
    type: Function,
    required: true,
  },
})

// 解构 todo 对象为响应式引用
const { value: localTodoValue, check, id } = toRefs(props.todo)

function handleCheck() {
  props.checkTodo(id.value)
}

// 删除的方法
function handleDelete() {
  props.deleteTodo(id.value)
}

// 转换编辑状态
function editTodo() {
  editing.value = true
  // 将 localTodoValue 设置为 todo.value 的当前值
  localTodoValue.value = props.todo.value
  // 聚焦输入框,防止闪烁
  setTimeout(() => {
    if (editableInput.value) {
      editableInput.value.focus();
    }
  }, 0)
}

// 保存编辑后的待办事项
function saveTodo() {
    // 将 todo.value 更新为编辑后的值
  props.todo.value = localTodoValue.value;
  editing.value = false
}
</script>
<style>
.custom-checkbox{
    margin-right: 10px;
    cursor: pointer;
    width: 20px;
    height: 15px;
    border-radius: 50%;
}

.checkbox-label {
  display: inline-block;
  position: relative;
  cursor: pointer;
}

.line {
  text-decoration: line-through;
}
</style>
